package com.uzai.console.service.pdd.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.SysMsgTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.CommonUtil;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.turnlink.PddTokenRecordDto;
import com.uzai.console.dto.locallive.tlbtoken.TlbTokenIdDto;
import com.uzai.console.dto.pdd.pddtoken.PddTokenCallBackDto;
import com.uzai.console.dto.pdd.pddtoken.PddTokenIdDto;
import com.uzai.console.dto.pdd.pddtoken.PddTokenInfoDto;
import com.uzai.console.dto.pdd.pddtoken.PddTokenQuery;
import com.uzai.console.entity.Merchant;
import com.uzai.console.entity.PddToken;
import com.uzai.console.entity.TlbToken;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.mapper.PddTokenMapper;
import com.uzai.console.mapper.TlbTokenMapper;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.service.pdd.PddTokenService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.vo.locallive.tlbtoken.TenMillionSubsidiesVo;
import com.uzai.console.vo.pdd.pddtoken.PddTokenAuthUrlVo;
import com.uzai.console.vo.pdd.pddtoken.PddTokenCallBackVo;
import com.uzai.console.vo.pdd.pddtoken.PddTokenInfoVo;
import com.uzai.console.vo.pdd.pddtoken.PddTokenRecordVo;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 多多进宝联盟
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PddTokenServiceImpl implements PddTokenService {

    Logger logger = LoggerFactory.getLogger(PddTokenServiceImpl.class);

    @Autowired
    private PddTokenMapper pddTokenMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private UzaiTurnlinkFeignService uzaiTurnlinkFeignService;
    @Autowired
    private TlbTokenMapper tlbTokenMapper;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

   /**
     * 查询拼多多联盟列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddTokenQuery
     * @return null
     */
    public Page<PddTokenInfoVo> findPddTokenList(PddTokenQuery pddTokenQuery){
        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<PddTokenInfoVo> pddTokenPageVoList = new ArrayList<>();

        //查询7天内到期的token
        if(pddTokenQuery.getExpireType() != null && pddTokenQuery.getExpireType().intValue() == 1){
            Integer time_7_days = DateUtil.getNowTime() + 604800;
            pddTokenQuery.setExpireTime(time_7_days);
        }

        //执行分页查询对象
        Page<PddToken> page = new Page<>();
        pddTokenQuery.convert(page);
        ArrayList<PddToken> pddOrderList =  pddTokenMapper.findByList(page, pddTokenQuery);
        if(pddOrderList != null && pddOrderList.size() > 0){
            for (PddToken pddToken : pddOrderList){
                PddTokenInfoVo pddTokenPageVo = new PddTokenInfoVo();
                BeanUtils.copyProperties(pddToken, pddTokenPageVo);
                //到期日期
                pddTokenPageVo.setExpirestime(Tools.getInteger(pddToken.getExpiresin()).intValue() + Tools.getInteger(pddToken.getAuthTime()).intValue());
                //到期时间
                Integer expiretime = Tools.getInteger(pddTokenPageVo.getExpirestime());
                if(expiretime.intValue() <= now.intValue()){
                    pddTokenPageVo.setExpireStatus(0);  //已到期
                }else if(expiretime.intValue() > now && expiretime.intValue() <= now + 7*24*3600){
                    pddTokenPageVo.setExpireStatus(2);  //即将到期
                }else{
                    pddTokenPageVo.setExpireStatus(1);  //未到期
                }

                pddTokenPageVoList.add(pddTokenPageVo);
            }
        }

        //返回到页面分页对象
        Page<PddTokenInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(pddTokenPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

   /**
     * 添加授权
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public PddTokenAuthUrlVo addPddToken(Long merId){
        //刷新授权的链接，将运营商ID放入自定义参数state当中，授权刷新之后，拼多多调用回调函数返回授权信息
        String url =  uzaiConsoleSysConfig.getPddTokenAuthorize() + "v3" + merId;
        PddTokenAuthUrlVo pddTokenAuthUrlVo = new  PddTokenAuthUrlVo();
        pddTokenAuthUrlVo.setUrl(url);
        return pddTokenAuthUrlVo;
    }

   /**
     * 查询联盟详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddTokenIdDto
     * @return null
     */
    public PddTokenInfoVo findPddTokenInfo(PddTokenIdDto pddTokenIdDto){

        if(pddTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        PddToken pddToken = pddTokenMapper.selectById(pddTokenIdDto.getId(), pddTokenIdDto.getMerId());
        if(pddToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该拼多多联盟账号不存在");
        }

        //返回页面对象
        PddTokenInfoVo pddTokenInfoVo = new PddTokenInfoVo();
        //将查询到的对象复制给返回页面对象
        BeanUtils.copyProperties(pddToken, pddTokenInfoVo);
        //到期日期
        pddTokenInfoVo.setExpirestime(Tools.getInteger(pddToken.getExpiresin()) + Tools.getInteger(pddToken.getAuthTime()));
        return pddTokenInfoVo;
    }

   /**
     * 修改联盟PID
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddTokenInfoDto
     * @return null
     */
    public void updatePid(PddTokenInfoDto pddTokenInfoDto){

        if(pddTokenInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if(pddTokenInfoDto.getDefPid() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入默认PID");
        }

        PddToken pddToken = pddTokenMapper.selectById(pddTokenInfoDto.getId(), pddTokenInfoDto.getMerId());
        if(pddToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该拼多多账号不存在");
        }

        pddToken.setDefPid(pddTokenInfoDto.getDefPid());
        pddToken.setRemark(pddTokenInfoDto.getRemark());

        pddTokenMapper.updateById(pddToken);
    }

   /**
     * 保存（兼容添加和修改）
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddToken
     * @return null
     */
    public void save(PddToken pddToken) {

        Merchant merchant = merchantMapper.selectById(pddToken.getMerId());
        if (merchant==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "没有该运营商");
        }

        PddToken at = pddTokenMapper.selectByUserId(pddToken.getUserId());
        //该淘宝联盟账号不存在，则新增加
        if (at == null){
            pddTokenMapper.insert(pddToken);

            //发送其他异常提醒
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(merchant.getId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OTHER_EXCEPTION.getValue()); //其他异常提醒
            //消息
            JSONObject ext = new JSONObject();
            StringBuilder content = new StringBuilder();
            content.append("拼多多已增加联盟授权，账号").append(pddToken.getUserId());
            //当前操作员
            ext.put("content", content.toString());
            ext.put("phone", merchant.getMobile());
            ext.put("errorcode", content.toString());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---拼多多添加联盟授权，发送其他异常消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));
            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

        }else {
            logger.info(at.getMerId() + "::" + pddToken.getMerId());
            if (at.getMerId().longValue() != pddToken.getMerId().longValue()){
                Merchant merchant1 = merchantMapper.selectById(at.getMerId());
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.PDD_ACCOUNT_EXIST, CommonUtil.mobileFormat(merchant1.getMobile())));
            }
            pddToken.setId(at.getId());
            int count = pddTokenMapper.updateByIdSelective(pddToken);
            if (count != 1){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.NET_ERROR);
            }
        }
    }

   /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddTokenIdDto
     * @return null
     */
    public void deletePddToken(PddTokenIdDto pddTokenIdDto){
        if(pddTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        pddTokenMapper.deleteById(pddTokenIdDto.getId(), pddTokenIdDto.getMerId());
    }

    /**
     * 授权
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddTokenCallBackDto
     * @return null
     */
    public void pddOauth(PddTokenCallBackDto pddTokenCallBackDto) {

        String state = pddTokenCallBackDto.getState();
        if(StringUtils.isBlank(state)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "自定义参数不能为空");
        }

        //获取系统版本
        String version = state.substring(0,2);
        //去掉前面2位版本号，为merId_type拼凑的参数
        state = state.substring(2);

        if(StringUtils.isBlank(pddTokenCallBackDto.getTokenInfo())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "token数据不能为空");
        }

        PddTokenCallBackVo pddTokenCallBackVo = JSONObject.parseObject(pddTokenCallBackDto.getTokenInfo(), PddTokenCallBackVo.class);

        logger.info(" pdd token  response = " + pddTokenCallBackVo.getAccessToken() + "||"  + pddTokenCallBackVo.getExpiresIn() + "||" + pddTokenCallBackVo.getOwnerName()+ "||" + pddTokenCallBackVo.getOwnerId());

        if(pddTokenCallBackVo == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "token数据格式不正确");
        }

        int now = DateUtil.getNowTime();
        PddToken pddToken = new PddToken();
        pddToken.setId(IdWorker.getId());
        pddToken.setAccessToken(pddTokenCallBackVo.getAccessToken());
        pddToken.setAuthTime(now);
        pddToken.setExpiresin(pddTokenCallBackVo.getExpiresIn());
        pddToken.setRefreshToken(pddTokenCallBackVo.getRefreshToken());
        pddToken.setUserId(pddTokenCallBackVo.getOwnerId());
        pddToken.setUserName(pddTokenCallBackVo.getOwnerName());
        pddToken.setCreateTime(now);
        pddToken.setUpdateTime(now);

        //3.0系统调用授权
        if("v3".equals(version)){
            pddToken.setMerId(Long.parseLong(state));
            save(pddToken);
        }else{ //2.0系统调用授权，则刷新授权
            PddToken pddToken_old = pddTokenMapper.selectByUserId(pddToken.getUserId());
            if(pddToken_old != null){//刷新授权
                pddToken_old.setUserName(pddToken.getUserName());
                pddToken_old.setAccessToken(pddToken.getAccessToken());
                pddToken_old.setRefreshToken(pddToken.getRefreshToken());
                pddToken_old.setExpiresin(pddToken.getExpiresin());
                pddToken_old.setReExpiresin(pddToken.getReExpiresin());
                pddToken_old.setAuthTime(now);
                pddToken_old.setUpdateTime(now);
                pddTokenMapper.updateById(pddToken_old);
            }
        }
    }


    @Override
    public List<PddToken> listPddToken(Long merId, List<Long> leagueAccountIds) {
        if (Objects.isNull(merId) || CollectionUtil.isEmpty(leagueAccountIds)) {
            return Lists.newArrayList();
        }
        LambdaQueryWrapper<PddToken> condition = Wrappers.lambdaQuery(PddToken.class);
        condition.eq(PddToken::getMerId, merId).in(PddToken::getId, leagueAccountIds);
        return pddTokenMapper.selectList(condition);
    }

    @Override
    public PddToken getPddToken(Long merId, Long leagueAccountId) {
        if (Objects.isNull(merId) || Objects.isNull(leagueAccountId)) {
            return null;
        }
        LambdaQueryWrapper<PddToken> condition = Wrappers.lambdaQuery(PddToken.class);
        condition.eq(PddToken::getMerId, merId).eq(PddToken::getId, leagueAccountId);
        return pddTokenMapper.selectOne(condition);
    }

    /**
     * 备案
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddTokenIdDto
     * @return null
     */
    public PddTokenRecordVo recordPddToken(PddTokenIdDto pddTokenIdDto){

        if(pddTokenIdDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        //是否是多多进宝
        PddToken pddToken = pddTokenMapper.selectById(pddTokenIdDto.getId(), pddTokenIdDto.getMerId());
        //是否是拼多多共享联盟
        TlbToken tlbToken = tlbTokenMapper.selectById(pddTokenIdDto.getId(), pddTokenIdDto.getMerId());
        if(pddToken == null && tlbToken == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该多多进宝或者推老板联盟");
        }

        //新增免单备案-免单备案只针对多多进宝联盟
        if(pddToken != null){
            //调用拼多多联盟备案接口
            PddTokenRecordDto pddTokenRecordDto_md = new PddTokenRecordDto();
            pddTokenRecordDto_md.setCustomParam("MD_" + pddTokenIdDto.getMerId());
            pddTokenRecordDto_md.setTokenId(pddTokenIdDto.getId());
            UzaiRespVo<String> uzaiRespVo_md = uzaiTurnlinkFeignService.pddCheckAuthority(pddTokenRecordDto_md);
            logger.info("--免单配置方案调用拼多多联盟备案接口--，para={},result={}", JSONObject.toJSONString(pddTokenRecordDto_md), JSONObject.toJSONString(uzaiRespVo_md));
            if(uzaiRespVo_md != null && uzaiRespVo_md.getCode() == 200 ){ //调用成功
                //如果返回data为空，则表示已经备案过
                if(StringUtils.isNotBlank(uzaiRespVo_md.getData())){
                    //将免单备案链接保持到数据库当中
                    pddToken.setMdRecordUrl(uzaiRespVo_md.getData());
                    pddTokenMapper.updateByIdSelective(pddToken);
                }
            }else{
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo_md == null || StringUtils.isBlank(uzaiRespVo_md.getMsg())? "请求备案失败!" : uzaiRespVo_md.getMsg());
            }
        }

        //普通备案
        PddTokenRecordVo pddTokenRecordVo = new PddTokenRecordVo();
        //调用拼多多联盟备案接口
        PddTokenRecordDto pddTokenRecordDto = new PddTokenRecordDto();
        pddTokenRecordDto.setCustomParam(String.valueOf(pddTokenIdDto.getMerId()));
        pddTokenRecordDto.setTokenId(pddTokenIdDto.getId());
        UzaiRespVo<String> uzaiRespVo = uzaiTurnlinkFeignService.pddCheckAuthority(pddTokenRecordDto);
        logger.info("--远程调用拼多多联盟备案接口--，para={},result={}", JSONObject.toJSONString(pddTokenRecordDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200 ){ //调用成功
            //如果返回data为空，则表示已经备案过
            if(StringUtils.isNotBlank(uzaiRespVo.getData())){
                pddTokenRecordVo.setRecordStatus(0); //未备案
                pddTokenRecordVo.setRecordUrl(uzaiRespVo.getData());
                //将备案链接保持到数据库当中
                if(pddToken != null){
                    pddToken.setRecordUrl(uzaiRespVo.getData());
                    pddTokenMapper.updateByIdSelective(pddToken);
                }else{
                    if(tlbToken != null ){
                        tlbToken.setRecordUrl(uzaiRespVo.getData());
                        tlbTokenMapper.updateByIdSelective(tlbToken);
                    }
                }
            }else{
                pddTokenRecordVo.setRecordStatus(1); //已经备案
            }
        }else{
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo == null || StringUtils.isBlank(uzaiRespVo.getMsg())? "请求备案失败!" : uzaiRespVo.getMsg());
        }

        return pddTokenRecordVo;
    }

    /**
     * 千万补贴
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddTokenIdDto
     * @return null
     */
    public TenMillionSubsidiesVo tenMillionSubsidies(PddTokenIdDto pddTokenIdDto){

        if(pddTokenIdDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }


        TlbToken tlbToken = tlbTokenMapper.selectById(pddTokenIdDto.getId(), pddTokenIdDto.getMerId());
        if(tlbToken == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "推老板共享联盟不存在");
        }

        TenMillionSubsidiesVo tenMillionSubsidiesVo = new TenMillionSubsidiesVo();
        //调用拼多多联盟备案接口
        PddTokenRecordDto pddTokenRecordDto_tk = new PddTokenRecordDto();
        pddTokenRecordDto_tk.setCustomParam(String.valueOf(pddTokenIdDto.getMerId()));
        pddTokenRecordDto_tk.setTokenId(pddTokenIdDto.getId());
        //14-千万补贴B端页面(淘客)
        pddTokenRecordDto_tk.setChannelType(14);
        UzaiRespVo<String> uzaiRespVo_tk = uzaiTurnlinkFeignService.pddGenRpurl(pddTokenRecordDto_tk);

        logger.info("--远程调用拼多多联盟千万补贴B端页面(淘客)接口--，para={},result={}", JSONObject.toJSONString(pddTokenRecordDto_tk), JSONObject.toJSONString(uzaiRespVo_tk));

        if(uzaiRespVo_tk != null && uzaiRespVo_tk.getCode() ==200 ){ //调用成功
            tenMillionSubsidiesVo.setTkPageUrl(uzaiRespVo_tk.getData());
            tlbToken.setTkPageUrl(uzaiRespVo_tk.getData());
        }else{
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo_tk == null || StringUtils.isBlank(uzaiRespVo_tk.getMsg())? "请求淘客页面失败" : uzaiRespVo_tk.getMsg());
        }

        //16-千万补贴C端页面(会员)
        PddTokenRecordDto pddTokenRecordDto_user = new PddTokenRecordDto();
        pddTokenRecordDto_user.setCustomParam(String.valueOf(pddTokenIdDto.getMerId()));
        pddTokenRecordDto_user.setTokenId(pddTokenIdDto.getId());
        pddTokenRecordDto_user.setChannelType(16);
        UzaiRespVo<String> uzaiRespVo_user = uzaiTurnlinkFeignService.pddGenRpurl(pddTokenRecordDto_user);

        logger.info("--远程调用拼多多联盟千万补贴C端页面(会员)接口--，para={},result={}", JSONObject.toJSONString(pddTokenRecordDto_user), JSONObject.toJSONString(uzaiRespVo_user));

        if(uzaiRespVo_user != null && uzaiRespVo_user.getCode() ==200 ){ //调用成功
            tenMillionSubsidiesVo.setUserPageUrl(uzaiRespVo_user.getData());
            tlbToken.setUserPageUrl(uzaiRespVo_user.getData());
        }else{
            throw new BusinessException(uzaiRespVo_user.getCode(), uzaiRespVo_user == null || StringUtils.isBlank(uzaiRespVo_user.getMsg())? "请求会员页面失败" : uzaiRespVo_user.getMsg());
        }

        //保持千万补贴申请页面
        tlbTokenMapper.updateByIdSelective(tlbToken);

        return tenMillionSubsidiesVo;
    }

}
